package org.example.pdf2word;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @Author : zhangbo
 * @data : 2025/1/15
 * @description :二进制数字转汉字
 */
@Slf4j
public class Demo4 {
    /**
     *     读取二进制数据 ||--o{ 将二进制数据转换为字节数组 : "读取到的二进制数据"
     *     将二进制数据转换为字节数组 ||--o{ 将字节数组转换为字符串 : "转换后的字节数组"
     *     将字节数组转换为字符串 ||--o{ 输出转换后的字符串 : "转换后的字符串"
     * @param args
     */
    public static void main(String[] args) throws Exception {

        String binaryStr ="110001000010001 111001000110001 100111101100000 1111111100001100 1001000010110101 100111000111101 101101000011111";
//        String string = binaryStr.replaceAll("\\s+", "");
//        log.info("处理后的而精致数据:" + string);
        System.out.println(BinstrToChar(binaryStr));
        System.out.println("---------------------");
        File file=new File("E:\\aa.bin\\");
        FileInputStream inputStream=new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        Charset charset=Charset.forName("UTF-8");
        String str=new String(bytes,charset);
        System.out.println(str);
        System.out.println("**************");
//        String chinese = binaryToChinese(binaryStr.replace(" ", "").trim());


    }

    public static String BinStrTostr(String binary) {
        String[] tempStr=binary.split(" ");
        char[] tempChar=new char[tempStr.length];
        for(int i=0;i<tempStr.length;i++) {
            tempChar[i]=BinstrToChar(tempStr[i]);
        }
        return String.valueOf(tempChar);
    }

    //将二进制转换成字符
    public static char BinstrToChar(String binStr){
        int[] temp=BinstrToIntArray(binStr);
        int sum=0;
        for(int i=0; i<temp.length;i++){
            sum +=temp[temp.length-1-i]<<i;
        }
        return (char)sum;
    }
    //将二进制字符串转换成int数组
    public static int[] BinstrToIntArray(String binStr) {
        char[] temp=binStr.toCharArray();
        int[] result=new int[temp.length];
        for(int i=0;i<temp.length;i++) {
            result[i]=temp[i]-48;
        }
        return result;
    }

    public static String binaryToChinese(String binaryStr) {
        int length = binaryStr.length();
        log.info(String.valueOf(length));
        // 将二进制字符串转换为字节数组
        byte[] bytes = new byte[binaryStr.length() / 8];
        for (int i = 0; i < bytes.length * 8; i += 8) {
            bytes[i / 8] = (byte) Integer.parseInt(binaryStr.substring(i, i + 8), 2);
        }
        try {
            // 使用UTF-8编码将字节数组转换为字符串
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
